package com.mybed.crm.controller;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mybed.crm.anno.Log;
import com.mybed.crm.common.enums.HttpCodeEnum;
import com.mybed.crm.exception.BaseException;
import com.mybed.crm.pojo.dto.*;
import com.mybed.crm.pojo.pojo.Role;
import com.mybed.crm.pojo.pojo.User;
import com.mybed.crm.pojo.vo.UserVo;
import com.mybed.crm.result.*;
import com.mybed.crm.service.RoleService;
import com.mybed.crm.service.UserService;
import com.mybed.crm.utils.thread.UserThreadLocalUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    /**
     * 转派管理选择部门后显示的人员
     */
    @GetMapping("/listselect")
    public Result listselect(Integer deptId){
        return userService.listselect(deptId);
    }

    /**
     * 分页查询用户
     * @param dto
     * @return
     */
    @GetMapping("/list")
    public PageResult list(PageUserDto dto){
        return userService.listUser(dto);
    }

    /**
     * 获取角色列表
     *
     * @return
     */
    @GetMapping("/")
    public RoleResult getRole(){
        List<Role> list = roleService.list();
        RoleResult result=new RoleResult();
        result.setRoles(list);
        result.setCode(HttpCodeEnum.SUCCESS.getCode());
        result.setMsg(HttpCodeEnum.SUCCESS.getErrorMessage());
        return result;
    }
    @Log("新增人员")
    @PostMapping
    public ResultP addUser(@RequestBody UserDto dto){
        User one = userService.getOne(Wrappers.<User>lambdaQuery().eq(User::getUserName, dto.getUserName()));
        if(one!=null){
            throw new BaseException("存在重复用户名字");
        }
        User user = userService.getById(UserThreadLocalUtil.getUser());
        User addUser=new User();
        BeanUtils.copyProperties(dto,addUser);
        addUser.setCreateBy(user.getUserName());
        addUser.setCreateTime(user.getCreateTime());
        addUser.setRoleIds(StringUtils.collectionToCommaDelimitedString(dto.getRoleIds()));
        String salt = UUID.randomUUID().toString();
        addUser.setSalt(salt);
        String md5 = SecureUtil.md5(addUser.getPassword() + salt);
        addUser.setPassword(md5);
        userService.save(addUser);
        return ResultP.success();
    }

    /**
     * 查询修改用户详情
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public UserResult updateUser(@PathVariable Integer id){
        return userService.updateUser(id);
    }
    @Log("修改用户")
    @PutMapping
    public ResultP updateByUser(@RequestBody UserVo vo){
        userService.updateByUser(vo);
        return ResultP.success();
    }
    @Log("重置密码")
    @PutMapping("/resetPwd")
    public ResultP resetPwd(@RequestBody ResetPwdDto dto){
        if(!StringUtils.hasLength(dto.getPassword())){
            throw new BaseException("密码不能为空");
        }
        User user = userService.getById(dto.getUserId());
        String md5 = SecureUtil.md5(dto.getPassword() + user.getSalt());
        user.setPassword(md5);
        userService.updateById(user);
        return ResultP.success();
    }
    @DeleteMapping("/{ids}")
    public ResultP removeUser(@PathVariable String ids){
        List<Integer> list = Arrays.stream(ids.split(",")).map(Integer::parseInt).collect(Collectors.toList());
        userService.removeBatchByIds(list);
        return ResultP.success();
    }
    @Log("修改用户状态")
    @PutMapping("/changeStatus")
    public ResultP changeStatus(@RequestBody UserStatusDto dto){
        User user = userService.getById(dto.getUserId());
        user.setStatus(dto.getStatus());
        userService.updateById(user);
        return ResultP.success();
    }

}
